package reportdb

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/boltdb/bolt"
	"report/constant"
	"report/model"
)

func AddOrUpdateProduct(product model.Product) error {
	err := reportDB.Update(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte(constant.PRODUCT_TABLE))
		if err != nil {
			return fmt.Errorf("create bucket: %s", err)
		}
		byt, _ := json.Marshal(product)
		return b.Put([]byte(product.Name), byt)
	})
	return err
}

func RemoveProduct(productName string) error {
	err := reportDB.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(constant.PRODUCT_TABLE))
		return b.Delete([]byte(productName))
	})
	return err
}

func GetProductByName(productName string) ([]byte, error) {
	var result []byte
	err := reportDB.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(constant.PRODUCT_TABLE))
		data := b.Get([]byte(productName))
		result = make([]byte, len(data))
		copy(result, data)
		return nil
	})
	return result, err
}

func GetAllProducts() ([]byte, error) {
	var buffer bytes.Buffer
	err := reportDB.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(constant.PRODUCT_TABLE))
		err := b.ForEach(func(_, v []byte) error {
			buffer.Write(v)
			return nil
		})
		return err
	})
	return buffer.Bytes(), err
}
